import $ from 'zepto-touch';
import { isPhone, isIos, isIE } from './platform';
import postscribe from 'postscribe';

/**
 * [判断js对象数据类型]
 * @param  {[type]} obj [description]
 * @return {[type]}     [description]
 */
let type = (obj) => Object.prototype.toString.call(obj).replace('[object ', '').replace(']', '').toLowerCase();

/**
 * [tools 使用频率想对比较低的工具]
 * @type {Object}
 */
let tools = {
    hasSticky: false,
    cacheTop: -1,
    /**
     * [stayTop 驻顶效果]
     * @param  {[type]} $catpion   [要驻顶的元素]
     * @param  {[type]} $ul        [驻顶后滚动列表的容器]
     * @param  {[type]} ulCallback [驻顶后,列表容器(动态)回调,需$ul传空值]
     * @return {[type]}            [description]
     */
    stayTop: function($catpion, $ul, ulCallback) {
        // HTMLDivElement
        if (type($catpion) === 'htmldivelement' || type($ul) === 'htmldivelement') {
            $catpion = $($catpion);
            $ul = $($ul);
        }
        let self = tools;
        let $body = $('body');
        let fixClass = 'p-fix';
        let hasFixClass = $catpion.hasClass(fixClass);
        let captionOffTop = $catpion[0].offsetTop;
        let bodyScrollTop = $body.scrollTop();

        if (!$ul && ulCallback) {
            $ul = ulCallback(null);
        }

        if (isIos() && false) {
            if (!self.hasSticky) {
                $catpion.addClass('sticky');
                self.hasSticky = true;
            }
        } else {
            if (self.cacheTop === -1) self.cacheTop = captionOffTop;

            if (~self.cacheTop) {
                if (bodyScrollTop < self.cacheTop) {
                    if (hasFixClass) {
                        $catpion.removeClass(fixClass);
                        $ul.css('paddingTop', 0);
                    }
                } else {
                    if (!hasFixClass) {
                        $catpion.addClass(fixClass);
                        $ul.css('paddingTop', '30px');
                    }
                }
            }
        }
    },
    /**
     * [iSliderImg 轮播图数据处理]
     * @param  {[type]} datas [处理数据]
     * @param  {[type]} opts  [选项: key,图片数据的key,string; suffix,图片后缀,string; attrs,自定义属性,array; ]
     * @return {[type]}       [description]
     */
    iSliderImg: function(datas, opts) {
        datas = datas || [];
        opts = opts || {};
        let iSliderImg = [];
        let imgSrc;
        let imgUrl = '';
        let attr = '';
        let attrs = opts.attrs;
        let attrKey = '';
        datas.forEach(function(data, index) {
            imgUrl = data[opts.key];
            attr = '';
            if (imgUrl) { // here does not support continue syntax
                imgSrc = imgUrl + (opts.suffix || '');
                if (attrs) {
                    for (attrKey in attrs) {
                        attr += ' data-' + attrKey + '="' + data[attrs[attrKey]] + '"';
                    }
                }
                iSliderImg[index] = {
                    content: '<img src="' + imgSrc + '" ' + attr + '/>',
                    src: imgSrc
                };
            }
        });
        return iSliderImg;
    },
    /**
     * [suffixClip 图片后缀,统一]
     * @return {[type]} [description]
     */
    suffixClip: function() {
        let winWidth = $(window).width();
        let dpr = window.devicePixelRatio || 1;
        let sWidth = 0;
        let sHeight = 0;
        sWidth = parseInt(winWidth * dpr);
        sHeight = parseInt(parseInt(winWidth * 400 / 750) * dpr);
        return (!isPhone() && $('body').width() === 640 ? '@s_2,w_640,h_340' : '@s_2,w_' + sWidth + ',h_' + sHeight);
    },
    /**
     * [lazyClipImg 图片处理,如果图片有设置大小，按照图片的大小进行剪切、压缩；否则按照图片/窗口宽度处理]
     * @param  {[type]} $selector [图片处理区域的选择器]
     * @param  {[type]} opts [{
     *                           errorSrc: '', // 错误的图片替换url
     *                       }]
     * @return {[type]}           [description]
     */
    lazyClipImg: function($selector, opts = {}) {
        let imgs;
        let width = 0;
        let height = 0;
        let suffix = '';
        let dpr = window.devicePixelRatio || 1;
        let winWidth = $(window).width();
        let opacity = -1;

        if ($selector[0]) {
            imgs = $selector.find('img');
            imgs.forEach(function(item, index) {
                let $img = $(item);
                let imgSrc; // 图片url，懒加载的图片
                width = $img.width();
                height = $img.height();
                imgSrc = $img.data('src');
                if (imgSrc && !~imgSrc.indexOf('file://')) {
                    if (!opts.isNotCup) {
                        let dprWidth = parseInt(width * dpr);
                        let dprHeight = parseInt(height * dpr);
                        var dprWinWidth = parseInt(winWidth * dpr);
                        suffix = height && width ? '@s_2,w_' + dprWidth + ',h_' + dprHeight : '@w_' + (dprWidth || dprWinWidth);
                    }
                    imgSrc = imgSrc.replace('http://', 'https://');   // 替换http图片为https
                    opacity = +$img.css('opacity');

                    // 如果透明度为0,则改为1
                    if (opacity === 0) $img.css({opacity: 1});

                    if (!~imgSrc.indexOf('https://bos')) suffix = ''; // dev环境下,其他图片加载
                    $img.attr('src', imgSrc + suffix).removeAttr('data-src');
                    $img.on('error', () => {
                        if (opts.errorSrc) $img.attr('src', opts.errorSrc);
                        else $img.remove();
                    });
                } else {
                    // 本地图片的话给remove掉
                    if (opts.errorSrc) $img.attr('src', opts.errorSrc);
                    else $img.remove();
                }
            });
        }
    },
    /**
     * [include 引入外部文件,使用这个公共函数的有：百度统计、百度地图、微信sdk、手百sdk]
     * @param  {[type]}   arrays   [[{id: '', url: '', timeout: 100, callback: function(){}}]]
     * @param  {Function} callback [全部ok后的回调]
     * @return {[type]}            [description]
     */
    include: function(arrays, callback) {
        if (arrays.length === 0) {
            if (callback) callback.call(tools);
            return;
        }
        let includeFile = arrays.shift() || {};
        let self = tools;
        let id = includeFile.id;
        if (id && includeFile.url) { // id and url was required for every included file
            if (!document.querySelector(`#${id}`)) {
                // 如果没有这个id,创建一个这个id的空白div
                let divEle = document.createElement('div');
                divEle.setAttribute('id', id);
                document.body.appendChild(divEle);

                // 加载外部库
                postscribe(`#${id}`, `<script src="${includeFile.url}"></script>`, {
                    done: function() {
                        if (includeFile.callback) includeFile.callback.call(self);
                        if (includeFile.timeout) {
                            setTimeout(function() {
                                self.include(arrays, callback);
                            }, includeFile.timeout);
                        } else {
                            self.include(arrays, callback);
                        }
                    }
                });
            } else {
                console.warn(`include this outside lib may be exists some error, please check your html element already contain this id(${id})`);
                self.include(arrays, callback);
            }
        } else {
            // console.warn('div id was not found');
            self.include(arrays, callback);
        }
    },
    /**
     * [getImgInfo 获取图片信息(宽度/高度)]
     * @param  {[type]} img   [description]
     * @param  {[type]} infos [description]
     * @return {[type]}       [description]
     */
    getImgInfo(imgUrl, infos) {
        let _type = type(imgUrl);
        let self = tools;
        // console.log('_type: ', _type);
        return new Promise((resolve, reject) => {
            switch (_type) {
                case 'array':
                    if (!infos) infos = [];
                    let _img = imgUrl.shift();
                    if (_img) {
                        self
                        .getImgInfo(_img, infos)
                        .then(imgInfo => {
                            infos.push(imgInfo);

                            self.getImgInfo(imgUrl, infos).then(resolve).catch(console.error);
                        })
                        .catch(console.error);
                    } else {
                        resolve(infos);
                    }
                    break;
                case 'string':
                    let img = new Image();
                    let imgInfo = null;
                    let successHandle = img => {
                        imgInfo = {
                            width: img.width,
                            height: img.height,
                            src: imgUrl
                        };
                        resolve(imgInfo);
                    };
                    /** [TODO: 错误处理,然后reject] */
                    if (isIE()) {
                        img.onreadystatechange = () => {
                            if (img.readyState === 'complete') {
                                successHandle(img);
                            }
                        };
                    } else {
                        img.onload = () => {
                            if (img.complete) {
                                successHandle(img);
                            }
                        };
                    }
                    img.src = imgUrl;
                    break;
                default:
                    let err = new Error(`unknow imgUrl's type: ${_type}`);
                    console.error(err);
                    reject(err);
                    break;
            }
        });
    }
};

export let stayTop = tools.stayTop;
export let iSliderImg = tools.iSliderImg;
export let suffixClip = tools.suffixClip;
export let lazyClipImg = tools.lazyClipImg;
export let include = tools.include;
export let getImgInfo = tools.getImgInfo;
export { type };
